package com.ma.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ma.gulimall.exception.NoStockException;
import com.ma.gulimall.to.mq.OrderTo;
import com.ma.gulimall.to.mq.StockDetailTo;
import com.ma.gulimall.to.mq.StockLockedTo;
import com.ma.gulimall.utils.PageUtils;
import com.ma.gulimall.utils.Query;
import com.ma.gulimall.utils.R;
import com.ma.gulimall.ware.dao.WareSkuDao;
import com.ma.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.ma.gulimall.ware.entity.WareOrderTaskEntity;
import com.ma.gulimall.ware.entity.WareSkuEntity;
import com.ma.gulimall.ware.feign.OrderFeignService;
import com.ma.gulimall.ware.feign.ProductFeignService;
import com.ma.gulimall.ware.service.WareOrderTaskDetailService;
import com.ma.gulimall.ware.service.WareOrderTaskService;
import com.ma.gulimall.ware.service.WareSkuService;
import com.ma.gulimall.ware.vo.*;
import com.rabbitmq.client.Channel;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    WareSkuDao wareSkuDao;

    @Autowired
    WareOrderTaskService orderTaskService;

    @Autowired
    WareOrderTaskDetailService orderTaskDetailService;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    OrderFeignService orderFeignService;

    @Autowired
    RabbitTemplate rabbitTemplate;


    /**
     * 02、查询商品库存
     * 请求参数
     * {wareId: 123,//仓库id
     * skuId: 123//商品id}
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();

        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId) && !"0".equalsIgnoreCase(skuId)) {
            queryWrapper.eq("sku_id", skuId);
        }

        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId) && !"0".equalsIgnoreCase(wareId)) {
            queryWrapper.eq("ware_id", wareId);
        }

        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                new QueryWrapper<WareSkuEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 添加库存
     */
    @Transactional
    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //判断是否有该库存信息，有则更新，无则新增
        List<WareSkuEntity> wareSkuEntities = wareSkuDao.selectList(
                new QueryWrapper<WareSkuEntity>()
                        .eq("sku_id", skuId).eq("ware_id", wareId));
        if (wareSkuEntities == null || wareSkuEntities.size() == 0) {
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(skuNum);
            // TODO: 2021/8/27 远程查询sku的名字，如果失败整个事件无需回滚
            //1、自己抛出异常
            // TODO: 2021/8/27 还可以用什么办法让异常出现后不回滚呢？
            try {
                R info = productFeignService.info(skuId);
                Map<String, Object> skuInfo = (Map<String, Object>) info.get("skuInfo");
                if (info.getCode() == 0) {
                    wareSkuEntity.setSkuName((String) skuInfo.get("skuName"));
                }
            } catch (Exception e) {

            }
            //添加库存信息
            wareSkuDao.insert(wareSkuEntity);
        } else {
            wareSkuDao.addStock(skuId, wareId, skuNum);
        }

    }

    /**
     * 判断是否有库存，返回skuId  与bool值
     * 用sql语句查询是否有库存，wms_ware_sku 表中对应sku_id的 stock-stock_locked > 0 表示有库存
     */
    @Override
    public List<SkuHasStockVo>
    getSkusHasStock(List<Long> skuIds) {
        List<SkuHasStockVo> skuHasStockVos = skuIds.stream().map(skuId -> {
            Long count = this.baseMapper.getSkuStock(skuId);
            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();
            skuHasStockVo.setSkuId(skuId);
            skuHasStockVo.setHasStock(count == null ? false : count > 0);
            return skuHasStockVo;
        }).collect(Collectors.toList());
        return skuHasStockVos;
    }

    /**
     * 为某个订单锁库存
     * 库存解锁的场景：
     * 1）、下订单成功，订单过期没有支付被取消、被用户手动取消。都要解锁库存
     * 2）、下订单成功，库存锁定成功，接下来的业务调用失败，导致订单回滚
     * 之前锁定的库存就要自动解锁。
     *
     * @param vo
     * @return
     * @Transactional(rollbackFor = NoStockException.class) 默认只要是运行时异常都会回滚
     */
    @Transactional(rollbackFor = NoStockException.class)
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {

        /**
         * 保存库存工作单的详情。
         * 追朔 用 `wms_ware_order_task_detail`表
         */
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(vo.getOrderSn());
        orderTaskService.save(taskEntity);

        //1、按照下单的收货地址，找到一个就近仓库，锁定库存
        //1、找到每个商品在哪个仓库都有库存
        List<OrderItemVo> locks = vo.getLocks();
        List<SkuWareHasStockVo> stocks = locks.stream().map(item -> {
            SkuWareHasStockVo stock = new SkuWareHasStockVo();
            Long skuId = item.getSkuId();
            stock.setSkuId(skuId);
            stock.setNum(item.getCount());
            List<Long> wareIds = wareSkuDao.listWareIdHasSkuStock(skuId);
            stock.setWareId(wareIds);
            return stock;
        }).collect(Collectors.toList());

        //2、锁定库存
        for (SkuWareHasStockVo hasStock : stocks) {
            boolean skuStocked = false;
            Long skuId = hasStock.getSkuId();
            List<Long> wareIds = hasStock.getWareId();
            if (CollectionUtils.isEmpty(wareIds)) {
                //没有任何仓库有这个商品的库存
                throw new NoStockException(skuId);
            }
            //1、如果每一个商品都锁定成功，将当前商品锁定了几件的工作单消息发送给mq
            //2、锁定失败：前面保存的工作单就回滚了。发送出去的消息，即使要解锁记录，由于去数据库查不到id，所以就不用解锁
            for (Long wareId : wareIds) {
                Long count = wareSkuDao.lockSkuStock(skuId, wareId, hasStock.getNum());
                if (count == 1) {
                    //==1锁成功   TODO: 2021/11/13 告诉MQ库存锁定成功
                    skuStocked = true;
                    WareOrderTaskDetailEntity taskDetailEntity = new WareOrderTaskDetailEntity(null, skuId, "",
                            hasStock.getNum(), taskEntity.getId(), wareId, 1);
                    orderTaskDetailService.save(taskDetailEntity);

                    StockLockedTo lockedTo = new StockLockedTo();
                    lockedTo.setId(taskEntity.getId());
                    StockDetailTo stockDetailTo = new StockDetailTo();
                    BeanUtils.copyProperties(taskDetailEntity, stockDetailTo);
                    lockedTo.setDetail(stockDetailTo);
                    /**
                     * 下单远程锁定库存，然后将仓库锁定库存的数据发给订单，当在订单下单失败时，由于不是分布式事务，
                     * 订单回滚库存没有回滚 所以订单一旦失败，就需要订单服务拿到消息队列中仓库传来的任务单数据来通知仓库解锁库存
                     */
                    rabbitTemplate.convertAndSend("stock-event-exchange", "stock.locked", lockedTo);


                    break;
                } else {
                    //当前仓库锁失败....重试下一个仓库
                }
            }
            if (skuStocked = false) {
                //当前商品所有商品都没有锁住
                throw new NoStockException(skuId);
            }
        }
        //3、全部都是锁定成功
        return true;
    }

    /**
     * 1、库存自动解锁。
     * ----->下单成功，库存锁定成功，接下来的业务调用失败，导致订单回滚。自己签的锁库存也要自动解锁
     * 2、订单失败。
     * ----->锁库存失败
     * <p>
     * !!!!只要解锁库存的消息失败。一定要告诉服务解锁失败。
     */
    //@RabbitHandler
    public void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {
        try {
            System.out.println("收到解锁库存的消息");
            StockDetailTo detail = to.getDetail();
            Long detailId = detail.getId();
        /*
          解锁：
          1、查询数据库关于这个订单的锁定库存信息
          -->有：证明库存锁定成功了
               解锁：订单状况
                   1、没有这个订单，必须解锁库存
                   2、有这个订单，不一定解锁库存
                       订单状态：已取消：解锁库存
                               已支付：不能解锁库存
          -->没有：库存锁定失败了，库存回滚，这个时候无需解锁
         */
            if (orderTaskDetailService.getById(detailId) != null) {
                //解锁  查出wms_ware_order_task工作单的信息
                Long id = to.getId();
                WareOrderTaskEntity orderTaskInfo = orderTaskService.getById(id);
                //获取订单号查询订单状态
                String orderSn = orderTaskInfo.getOrderSn();
                //远程查询订单信息
                R orderData = orderFeignService.getOrderStatus(orderSn);
                if (orderData.getCode() == 0) {
                    //订单数据返回成功
                    OrderVo orderInfo = orderData.getData("data", new TypeReference<OrderVo>() {
                    });
                    //判断订单状态是否已取消或者支付或者订单不存在
                    // 1、订单不存在：解锁
                    // 2、订单存在，且订单状态是取消状态：解锁
                    if (orderInfo == null || orderInfo.getStatus() == 4) {
                        unLockStocks(detail.getSkuId(), detail.getWareId(), detail.getSkuNum(), detailId);
                        //手动ACK
                        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                    }
                } else {
                    //远程调用服务失败
                    //消息拒绝以后重新放在队列里面，让别人继续消费解锁
                    channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
                    throw new RuntimeException("远程调用服务失败");
                }
            } else {
                //无需解锁[本来就没有锁定库存] 说明库存锁定失败，库存回滚，无需解锁
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            }
        } catch (Exception e) {
            //消息拒绝以后重新放在队列里面，让别人继续消费解锁
            System.out.println(e.getMessage());
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

    @Override
    public void unlockStock(StockLockedTo to) {
        StockDetailTo detail = to.getDetail();
        Long detailId = detail.getId();
        WareOrderTaskDetailEntity taskDetailInfo = orderTaskDetailService.getById(detailId);
        if (taskDetailInfo != null) {
            //解锁  查出wms_ware_order_task工作单的信息
            Long id = to.getId();
            WareOrderTaskEntity orderTaskInfo = orderTaskService.getById(id);
            //获取订单号查询订单状态
            String orderSn = orderTaskInfo.getOrderSn();
            //远程查询订单信息
            R orderData = orderFeignService.getOrderStatus(orderSn);
            if (orderData.getCode() == 0) {
                //订单数据返回成功
                OrderVo orderInfo = orderData.getData("data", new TypeReference<OrderVo>() {
                });
                //判断订单状态是否已取消或者支付或者订单不存在
                // 1、订单不存在：解锁
                // 2、订单存在，且订单状态是取消状态：解锁
                if (orderInfo == null || orderInfo.getStatus() == 4) {
                    if (taskDetailInfo.getLockStatus() == 1) {
                        //当前库存工作单详情状态1，已锁定，但是未解锁才可以解锁
                        unLockStocks(detail.getSkuId(), detail.getWareId(), detail.getSkuNum(), detailId);
                    }
                }
            } else {
                //远程调用服务失败
                //消息拒绝以后重新放在队列里面，让别人继续消费解锁
                throw new RuntimeException("远程调用服务失败");
            }
        } else {
            //无需解锁[本来就没有锁定库存] 说明库存锁定失败，库存回滚，无需解锁
        }

    }

    /**
     * 防止订单服务卡顿，导致订单状态消息一直改不了，库存优先到期，查订单状态新建，什么都不处理
     * 导致卡顿的订单，永远都不能解锁库存
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void unlockStock(OrderTo orderTo) {
        String orderSn = orderTo.getOrderSn();
        //查一下最新的库存解锁状态，防止重复解锁库存
        WareOrderTaskEntity orderTaskEntity = orderTaskService.getOrderTaskByOrderSn(orderSn);

        //按照工作单的id找到所有 没有解锁的库存，进行解锁
        Long id = orderTaskEntity.getId();
        List<WareOrderTaskDetailEntity> list = orderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>()
                .eq("task_id", id).eq("lock_status", 1));

        for (WareOrderTaskDetailEntity taskDetailEntity : list) {
            unLockStocks(taskDetailEntity.getSkuId(),
                    taskDetailEntity.getWareId(),
                    taskDetailEntity.getSkuNum(),
                    taskDetailEntity.getId());
        }
    }

    /**
     * 解锁库存的方法【设计DB，没加事务】
     */
    private void unLockStocks(Long skuId, Long wareId, Integer num, Long taskDetailId) {
        wareSkuDao.unlockStock(skuId, wareId, num);
        //更新工作单的状态
        WareOrderTaskDetailEntity taskDetailEntity = new WareOrderTaskDetailEntity();
        taskDetailEntity.setId(taskDetailId);
        //变为已解锁
        taskDetailEntity.setLockStatus(2);
        orderTaskDetailService.updateById(taskDetailEntity);
    }


}